/* jshint esversion: 6 */
let timer = null;
export function debounce(fn, wait = 1000, immediate = false) {  //防抖函数
    return function () {
        let args = arguments;
        let context = this;
        if (immediate && !timer) {
            fn.apply(context, args)
        }
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            fn.apply(context, args);
            clearTimeout(timer)
        }, wait);
    }
}


export function throttle(fn, wait, immediate) {
    // 节流
    let callNow = immediate;
    return function () {
        let context = this,
            args = arguments;
        if (callNow) {
            fn.apply(context, args);
            callNow = false
        }
        if (!timer) {
            timer = setTimeout(() => {
                fn.apply(context, args);
                clearTimeout(timer)
            }, wait)
        }
    }
}


let target = '';

export function deepFind(arr, id) {
    if (arr) {
        for (let i = 0; i < arr.length; i++) {
            if (arr[i].id === id) {
                target = arr[i];
                break;
            } else {
                target = ''
            }
            if (arr[i].deptList) {
                deepFind(arr[i].deptList, id)
            }
        }
        return target
    } else {
        return ''
    }
}

export function clear(data) {
    Object.keys(data).forEach(item => {
        data[item] = '';
    });
}

export function getArray(arr, children = 'deptList') {
    let arrs = [];
    for (let i = 0; i < arr.length; i++) {
        arrs.push(arr[i]);
        if (arr[i][children]) {
            arrs = arrs.concat(getArray(arr[i][children], children))
        }
    }
    return arrs;
}

export function getChecked(arr) {
    let arrs = [];
    for (let i = 0; i < arr.length; i++) {
        if (arr[i].checked) {
            arrs.push(arr[i].id)
        }
        if (arr[i].aclList) {
            arrs = arrs.concat(getChecked(arr[i].aclList));
        }
    }
    return arrs;
}

 //export const baseURL = process.env.NODE_ENV === 'production' ? 'http://47.100.240.34:8094' : 'http://iel-api.sh-inline.com/api';

export const baseURL = process.env.NODE_ENV === 'production' ? 'http://iel-api.sh-inline.com/api' : 'http://192.168.50.77:8080'; //'http://47.100.240.34:8094';

export function getFileName(name) {
    if (name) {
        return name.replace(/(.*\/)*([^.]+).*/ig, "$2") + '.' + name.substring(name.lastIndexOf('.') + 1);
    } else {
        return ''
    }

}

export function money(num) {
    return num && num.toString()
        .replace(/^\d+/g, (m) => m.replace(/(?=(?!^)(\d{3})+$)/g, ',')
        );
}

export function arrayUnique(arr) {
    if (arr && arr.length) {
        return [...new Set([...arr])];
    } else {
        return arr;
    }
}